package jfconfig;

/**
 * Created : Apr 3, 2012
 *
 * @author pquiring
 */

import java.io.*;
import java.util.Arrays;
import javax.swing.*;

import javaforce.*;
import javaforce.linux.*;

public class VPNPanel extends javax.swing.JPanel {

  /**
   * Creates new form VPNPanel
   */
  public VPNPanel() {
    initComponents();
    loadConfig();
  }

  /**
   * This method is called from within the constructor to initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is always
   * regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    jToolBar1 = new javax.swing.JToolBar();
    back = new javax.swing.JButton();
    add = new javax.swing.JButton();
    delete = new javax.swing.JButton();
    edit = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    list = new javax.swing.JList();

    jToolBar1.setFloatable(false);
    jToolBar1.setRollover(true);

    back.setText("< Back");
    back.setFocusable(false);
    back.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    back.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    back.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        backActionPerformed(evt);
      }
    });
    jToolBar1.add(back);

    add.setText("Add");
    add.setFocusable(false);
    add.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    add.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    add.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        addActionPerformed(evt);
      }
    });
    jToolBar1.add(add);

    delete.setText("Delete");
    delete.setFocusable(false);
    delete.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    delete.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    delete.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        deleteActionPerformed(evt);
      }
    });
    jToolBar1.add(delete);

    edit.setText("Edit");
    edit.setFocusable(false);
    edit.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    edit.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    edit.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        editActionPerformed(evt);
      }
    });
    jToolBar1.add(edit);

    list.setModel(model);
    jScrollPane1.setViewportView(list);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 448, Short.MAX_VALUE)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(jScrollPane1)
        .addContainerGap())
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 418, Short.MAX_VALUE)
        .addContainerGap())
    );
  }// </editor-fold>//GEN-END:initComponents

  private void addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addActionPerformed
    VPNDialog dialog = new VPNDialog(null, true, null);
    dialog.setVisible(true);
    if (!dialog.accepted) return;
    VPN newVPN = new VPN();
    dialog.get(newVPN);
    config.vpn = Arrays.copyOf(config.vpn, config.vpn.length + 1);
    config.vpn[config.vpn.length-1] = newVPN;
    updateConfig();
    saveConfig();
  }//GEN-LAST:event_addActionPerformed

  private void deleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteActionPerformed
    int idx = list.getSelectedIndex();
    if (idx == -1) return;
    int len = config.vpn.length;
    VPN newList[] = new VPN[len-1];
    System.arraycopy(config.vpn, 0, newList, 0, idx);
    System.arraycopy(config.vpn, idx+1, newList, idx, len - idx - 1);
    config.vpn = newList;
    updateConfig();
    saveConfig();
  }//GEN-LAST:event_deleteActionPerformed

  private void editActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editActionPerformed
    int idx = list.getSelectedIndex();
    if (idx == -1) return;
    VPNDialog dialog = new VPNDialog(null, true, config.vpn[idx]);
    dialog.setVisible(true);
    if (!dialog.accepted) return;
    dialog.get(config.vpn[idx]);
    updateConfig();
    saveConfig();
  }//GEN-LAST:event_editActionPerformed

  private void backActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backActionPerformed
    ConfigApp.This.setPanel(new NetworkPanel());
  }//GEN-LAST:event_backActionPerformed

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton add;
  private javax.swing.JButton back;
  private javax.swing.JButton delete;
  private javax.swing.JButton edit;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JToolBar jToolBar1;
  private javax.swing.JList list;
  // End of variables declaration//GEN-END:variables

  public static class VPN {
    public String name;
    public String host;
    public String caps;  //windows = pre-defined, else: pap, mschap, etc.
    public String capsOpts;  //flags
    public String routes;  //comma list
    public String routeOpts;  //flags
    public String user, pass, domain;
    public String domainsearch;
  }

  public static class Config {
    public VPN vpn[];
  }

  private DefaultListModel model = new DefaultListModel();
  private Config config;
  private String configFile = "/etc/jconfig.d/vpn.xml";

  private void loadConfig() {
    defaultConfig();
    try {
      XML xml = new XML();
      File tmpFile = File.createTempFile("vpn", ".xml");
      if (!Linux.copyFile(configFile, tmpFile.getAbsolutePath())) throw new Exception("copy failed");
      FileInputStream fis = new FileInputStream(tmpFile.getAbsoluteFile());
      xml.read(fis);
      xml.writeClass(config);
      tmpFile.delete();
    } catch (FileNotFoundException e1) {
      defaultConfig();
    } catch (Exception e2) {
      JFLog.log(e2);
      defaultConfig();
    }
    updateConfig();
  }

  private void defaultConfig() {
    config = new Config();
    config.vpn = new VPN[0];
  }

  private void updateConfig() {
    model.removeAllElements();
    for(int a=0;a<config.vpn.length;a++) {
      model.addElement(config.vpn[a].name);
    }
  }

  private void saveConfig() {
    try {
      XML xml = new XML();
      File tmpFile = File.createTempFile("vpn", ".xml");
      FileOutputStream fos = new FileOutputStream(tmpFile);
      Runtime.getRuntime().exec(new String[] {"chmod", "600", tmpFile.getAbsolutePath()});  //protect passwords
      xml.readClass("vpn", config);
      xml.write(fos);
      fos.close();
      if (!Linux.copyFile(tmpFile.getAbsolutePath(), configFile)) throw new Exception("copy failed");
      tmpFile.delete();
    } catch (Exception e) {
      JFLog.log(e);
    }
  }
}
